import NavBar from './components/NavBar'
import Menu from './components/Menu'
import Cart from './components/Cart'
import FoodsCategory from './components/FoodsCategory'

import './App.scss'
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { foodsActions } from './store/modules/foods'

const App = () => {

  const { foodsList, activeIndex } = useSelector(state => state.foods)

  // 获取dispatch函数
  const dispatch = useDispatch()

  // 不能放到外面发请求获取数据
  // 原因：这个App函数组件 每当状态发生变化，都需要重新执行，从而渲染最新的UI
  // dispatch( foodsActions.getFoodsList() )

  useEffect(() => {
    // 保证只会调用一次
    dispatch(foodsActions.getFoodsList())
  }, [dispatch])

  return (
    <div className="home">

      {/* 导航 */}
      <NavBar />

      {/* 内容 */}
      <div className="content-wrap">
        <div className="content">
          <Menu />

          <div className="list-content">
            <div className="goods-list">
              {/* 外卖商品列表 */}
              {/* foodsList 是所有的分类对象，具体的商品列表在分类对象中 */}
              {foodsList.map((item, index) => {
                return (
                  activeIndex === index && <FoodsCategory
                    key={item.tag}
                    // 列表标题
                    name={item.name}
                    // 列表商品
                    foods={item.foods}
                  />
                )
              })}
            </div>
          </div>
        </div>
      </div>

      {/* 购物车 */}
      <Cart />
    </div>
  )
}

export default App
